import { defineStore } from 'pinia';
import { getInfo, setInfo, removeInfo } from '../utils/auth';
import { login, logout } from '@/api/user';
import { ElMessage } from 'element-plus';
import { useAsyncRoutes } from './useAsyncRoutes';
export const useLoginInfo = defineStore('useLoginInfo', {
    state: () => {
        return {
            token: '' || getInfo('token')
        };
    },
    actions: {
        login(data: any) {
            //模拟接口请求返回数据
            return new Promise((resolve, reject) => {
                login(data)
                    .then((res) => {
                        const token = res.data?.token;
                        if (token) {
                            //登陆成功
                            this.token = token;
                            setInfo('token', token);
                            ElMessage.success(res.message || '登录成功');
                            resolve(res);
                        } else {
                            //抛出登陆失败的结果
                            reject({ err: res });
                        }
                    })
                    .catch((err) => {
                        //抛出接口异常
                        reject(err);
                    });
            });
        },
        logout() {
            return new Promise((resolve, reject) => {
                logout()
                    .then((res) => {
                        ElMessage.success(res.message || '退出登录成功');
                        this.resetToken();
                        resolve(res);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        // 清除token以及一系列操作
        resetToken() {
            this.token = '';
            removeInfo('token');
            //清除routers
            useAsyncRoutes().resetAllRoutes();
        }
    }
});
